<template>
  <ContainerGroup>
    <Container style="margin-bottom: 10px">
      <FilterForm
        ref="filterForm"
        :elements="elements"
        noimmediate
        @submit="handleSearch"
        @reset="handleReset"
      >
      <Button v-if="!imageShow" type="plain" icon="add" @click="handleAdd"
          >新增</Button
        >
        <Button v-if="!imageShow" type="plain" @click="handleInherit"
          >继承</Button
        >
        <Button
          v-if="!imageShow"
          type="hollow"
          icon="icon-daochu1"
          :btn-loading="dcLoading"
          @click="handleDealExcel"
          >导出</Button
        >
      </FilterForm>
    </Container>
    <Container height="fill">
      <div class="wraper">
        <div v-if="imageShow" class="image-srcc">
          <img src="../../../assets/image/archived.png" alt="" />
        </div>
        <Table
          :selection="true"
          :columns="conColums"
          :loading="tableLoading"
          :data="tableData"
          :pagination="{
            total: total,
            current: currentPage,
            pageSize: pageSize,
          }"
          @paginationChange="pageChange"
          @rowSelection="handleSelection"
        >
          <template #caozuo="{ row }">
            <Tooltip content="编辑" icon="edit" @click="handleEdit(row)" />
          </template>
        </Table>
      </div>
      <!-- 新增、编辑 -->
      <Drawer
        ref="drawerRef"
        :title="title"
        :visible.sync="showDrawer"
        width="420px"
        :footer-btns="[
          {
            text: '确认',
            type: 'primary',
            loading: qrLoading,
            trigger: 'submit',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @submit="handleSubmit"
        @cancel="showDrawer = false"
      >
        <el-form
          v-if="showDrawer"
          ref="drawerForm"
          :model="drawerForm"
          :rules="drawerRules"
          label-width="120px"
          size="mini"
          class="demo-drawerForm"
        >
          <div v-if="btnType === 1">
            <el-form-item label="核算单元：" prop="accounting">
              <el-select v-model="drawerForm.accounting" clearable placeholder="请选择">
                <el-option
                  v-for="item in accountingOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="工作量权重：" prop="workloadWeight">
              <el-input
                v-model.trim="drawerForm.workloadWeight"
                placeholder="请输入"
                maxlength="20"
                clearable
              />
            </el-form-item>
          </div>
          <div v-else>
            <el-form-item label="核算单元编码：" prop="accountingCode">
              <el-input
                v-model.trim="drawerForm.accountingCode"
                placeholder="请输入"
                :disabled="btnType === 2"
                maxlength="10"
                clearable
              />
            </el-form-item>
            <el-form-item label="核算单元名称：" prop="accountingName">
              <el-input
                v-model.trim="drawerForm.accountingName"
                placeholder="请输入"
                :disabled="btnType === 2"
                maxlength="20"
                clearable
              />
            </el-form-item>
            <el-form-item label="工作量权重：" prop="workloadWeight">
              <el-input
                v-model.trim="drawerForm.workloadWeight"
                placeholder="请输入"
                maxlength="20"
                clearable
              />
            </el-form-item>
            <el-form-item label="考核周期：" prop="assessmentCycle">
              <el-input
                v-model.trim="drawerForm.assessmentCycle"
                placeholder="请输入"
                :disabled="btnType === 2"
                maxlength="20"
                clearable
              />
            </el-form-item>
          </div>
        </el-form>
      </Drawer>
      <!-- 继承 -->
      <el-dialog
        title="继承"
        :visible.sync="centerDialogVisible"
        top="30vh"
        width="30%"
      >
        <div class="dialog-inherit">
          <span>继承周期：</span>
          <el-select v-model="inheritCycle" placeholder="请选择">
            <el-option
              v-for="item in elements[0].options"
              :key="item.id"
              :label="item.periodPull"
              :value="item.id"
            />
          </el-select>
        </div>
        <div class="dialog-inherit">
          <span>目标周期：</span>
          <el-select v-model="targetCycle" placeholder="请选择">
            <el-option
              v-for="item in elements[0].options"
              :key="item.id"
              :label="item.periodPull"
              :value="item.id"
            />
          </el-select>
        </div>
        <div class="dialog-but">
          <el-button @click="handleClaer">取消</el-button>
          <el-button type="primary" :loading="btnLoading" @click="handleConfim"
            >确认</el-button
          >
        </div>
      </el-dialog>
    </Container>
  </ContainerGroup>
</template>
<script>
import {
  listAccountingUnitWeightByPage,
  getAssessmentCyclePull,
  listAllAccountingUnit,
  isFile,
  updateAccountingUnitWeight,
  getExport,
  inheritAccountingUnitWeight,
  listAccountingVO,
  saveAccountingUnitWeight
} from "@/api/weight";
export default {
  data() {
    return {
      centerDialogVisible: false,
      dcLoading: false,
      kxList: [],
      qrLoading: false,
      btnType: 1,
      optionList: [],
      drawerForm: {
        assessmentCycle: "",
        accountingCode: "",
        accountingName: "",
        workloadWeight: "",
        accounting: ""
      },
      drawerRules: {
        assessmentCycle: [
          { required: true, message: "请输入考核周期", trigger: "change" },
        ],
        accountingCode: [
          { required: true, message: "请输入核算单元编码", trigger: "blur" },
        ],
        accountingName: [
          { required: true, message: "请输入核算单元名称", trigger: "blur" },
        ],
        workloadWeight: [
          { required: true, message: "请输入工作量权重", trigger: "blur" },
        ],
        accounting: [
          { required: true, message: "请选择核算单元", trigger: "change" },
        ],
      },
      darawerLoading: false,
      showDrawer: false,
      title: "",
      fileList: [],
      importLoading: false,
      tableColumns: [
        {
          title: "核算单元名称",
          dataIndex: "accountingName",
        },
        {
          title: "核算单元编码",
          dataIndex: "accountingCode",
        },
        {
          title: "工作量权重",
          dataIndex: "workloadWeight",
        },
        {
          title: "考核周期",
          dataIndex: "assessmentCycle",
        }
      ],
      total: 0,
      pageSize: 100,
      currentPage: 1,
      tableLoading: false,
      tableData: [],
      newCondition: {},
      elements: [
        {
          key: "cycle",
          label: "周期",
          type: "select",
          itemLabel: "periodPull",
          itemValue: "id",
          hideSelectAll: true,
          options: [],
          value: "",
        },
        {
          key: "accountingUnit",
          label: "核算单元",
          type: "select",
          itemLabel: "name",
          itemValue: "code",
          hideSelectAll: true,
          options: [],
          value: "",
        },
      ],
      currentRow: {},
      selections: [],
      inheritCycle: "",
      targetCycle: "",
      imageShow: false,
      btnLoading: false,
      accountingOptions: []
    };
  },
  computed: {
    conColums() {
      return this.imageShow
        ? this.tableColumns
        : [
            ...this.tableColumns,
            {
              title: "操作",
              dataIndex: "caozuo",
              type: "otherTag",
              width: 160,
            }
          ]
    }
  },
  created() {
    this.getSelect();
  },
  methods: {
    // 是否归档
    getIsFile() {
      const id = this.elements[0].options.find(item =>item.id===this.newCondition?.cycle)?.id
      const param = {
        id: id,
      };
      isFile(param).then((res) => {
        if (res.code === 200) {
          if (res.data === 0) {
            this.imageShow = false;
          } else if (res.data === 1) {
            this.imageShow = true;
          }
        }
      });
    },
    handleSelection(row) {
      this.selections = row;
    },
    handleDealExcel() {
      // 导出字典
      if (this.selections.length === 0) {
        this.$message.warning("请选择要导出的数据");
        return;
      }
      const params = {
        ids: this.selections.map((item) => item.id),
      };
      this.dcLoading = true;
      getExport(params).then((res) => {
        this.dcLoading = false;
        this.$utils.downloadFileFun(res, "核算单元权重配置管理.xls");
      });
    },
    getSelect() {
      // 周期
      getAssessmentCyclePull().then((res) => {
        if (res.code === 200) {
          this.elements[0].options = res.data;
          const { id } = res.data[0];
          this.elements[0].value = id;
          localStorage.setItem(
            "cycle",
            JSON.stringify(this.elements[0].options)
          );
          setTimeout(() => {
            this.handleSearch(this.$refs.filterForm.getParms())
          }, 1000)
        } else {
          this.$message.error(res.msg);
        }
      });
      // 核算单元
      listAllAccountingUnit().then((res) => {
        if (res.code === 200) {
          this.elements[1].options = res.data;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 新增 核算单元
    _listAccountingVO() {
      const param = {
        assessmentCycleId: this.elements[0].value
      }
      listAccountingVO(param).then(res => {
        if (res.code === 200) {
          this.accountingOptions = res.data
        }
      })
    },
    // 编辑--保存
    handleSubmit() {
      this.$refs["drawerForm"].validate((valid) => {
        if (/[\u4e00-\u9fa5]+/.test(this.drawerForm.accountingCode)) {
          this.$message.warning("核算单元编码不能包含中文");
          return;
        }
        if (!this.$isNull(this.drawerForm.workloadWeight)) {
          if (!/^\d+(\.\d+)?$/.test(this.drawerForm.workloadWeight)) {
            this.$message.warning("工作量权重需要数字类型");
            return;
          }
        }

        if (valid) {
            this.qrLoading = true;
          if (this.btnType === 1) {
            const param = {
              accountingCode: this.drawerForm.accounting,
              accountingName: this.accountingOptions.find(item => item.code === this.drawerForm.accounting)?.name,
              workloadWeight: this.drawerForm.workloadWeight,
              assessmentCycleId: this.newCondition.cycle
            }
            saveAccountingUnitWeight(param).then(res => {
              this.qrLoading = false;
              if (res.code === 200) {
                this.getData();
                this.showDrawer = false;
                this.$message.success(res.msg);
              } else {
                this.$message.error(res.msg);
              }
            })
          } else {
            const param = {
              ...this.drawerForm,
            };
            param.id = this.currentRow?.id;
            updateAccountingUnitWeight(param).then((res) => {
              this.qrLoading = false;
              if (res.code === 200) {
                this.getData();
                this.showDrawer = false;
                this.$message.success(res.msg);
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 查询
    handleSearch(value) {
      this.newCondition = value;
      this.currentPage = 1;
      this.getData()
      this.getIsFile();
    },
    // 重置
    handleReset(val) {
      this.handleSearch(val);
    },
    // 新增
    handleAdd() {
      this.btnType = 1;
      this.title = "新增核算单元权重";
      this.$handleSetForm(this.drawerForm, 0);
      this._listAccountingVO()
      this.showDrawer = true;
    },
    handleEdit(row) {
      // 编辑
      this.currentRow = row;
      this.btnType = 2;
      this.title = "编辑核算单元权重";
      this.handleSetForm(row);
      this.showDrawer = true;
    },
    handleSetForm(row) {
      this.$handleSetForm(this.drawerForm, 1, row);
    },
    // 继承
    handleInherit() {
      this.centerDialogVisible = true;
    },
    // 继承--取消
    handleClaer() {
      this.inheritCycle = "";
      this.targetCycle = "";
      this.centerDialogVisible = false;
    },
    // 继承--保存
    handleConfim() {
      const param = {
        inheritanceId: this.inheritCycle,
        targetId: this.targetCycle,
      };
      this.btnLoading = true;
      inheritAccountingUnitWeight(param)
        .then((res) => {
          this.btnLoading = false;
          if (res.code === 200) {
            this.$message.success(res.msg);
            this.handleClaer();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(() => {
          this.btnLoading = false;
        });
    },
    // 数据
    getData() {
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        assessmentCycleId: this.newCondition.cycle,
        accountingCode: this.newCondition.accountingUnit,
        // type: this.newCondition.type,
      };
      this.tableLoading = true;
      listAccountingUnitWeightByPage(params)
        .then((res) => {
          this.tableLoading = false;
          if (res.code === 200) {
            this.tableData = res.data.records;
            this.total = res.data.total;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    // 分页
    pageChange(payload) {
      this.currentPage = payload.current;
      this.pageSize = payload.pageSize;
      this.getData();
    },
  },
};
</script>
<style lang="less" scoped>
.wraper {
  display: flex;
  height: 100%;
  overflow: hidden;
  position: relative;
  .upload-demo {
    .buttons {
      margin: 0px 5px;
      height: 27px;
      margin-top: -1px;
    }
  }
}
/deep/.el-dialog__header {
  padding: 10px 10px 0px 10px;
  padding-bottom: 0px;
}
/deep/.el-dialog__title {
  font-size: 15px;
}
/deep/.el-dialog__headerbtn {
  top: 10px;
}
/deep/.el-dialog__body {
  padding: 10px;
}
.dialog-inherit {
  display: flex;
  flex-direction: row;
  margin: 10px;
  justify-content: center;
  span {
    margin-top: 5px;
  }
}
.dialog-but {
  margin: 10px;
  display: flex;
  flex-direction: row;
  justify-content: right;
}
// /deep/.el-table {
//   position: relative;
// }
.image-srcc {
  width: 60px;
  height: 60px;
  // border: 1px solid red;
  position: absolute;
  top: 5px;
  left: 190px;
  z-index: 2;
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
